// ==UserScript==
// @name         中税网
// @version      0.1
// @description  中税网挂课
// @author       Rainbow
// @match        https://kj.taxchina.com/shanghai/study*
// @run-at       document-idle
// @grant        none
// ==/UserScript==

(function () {
    var ulQueryStr = "#root > div > div.layout-basic-container > div > div.course-box > div:nth-child(2) > ul";
    var mediaButtonStr = "#vjs_video_3 > button"
    var mediaStr = "#vjs_video_3_html5_api"
    var currentActiveNodeNum = 0
    document.onreadystatechange = function () {
        if (document.readyState == "complete") {
            setTimeout(() => {
                init()
                currentActiveNodeNum = getCurrentActiveNode()
                playMedia()
                let video = document.querySelector(mediaStr)
                video.muted = true
                //每30秒检测视频是否暂停，暂停后继续播放
                setInterval(() => {
                    if(video.paused)
                    {
                        video.play()
                    }
                }, 30 * 1000);
                video.onended = function(){
                    currentActiveNodeNum++
                    clickLiNode(currentActiveNodeNum)
                    setTimeout(() => {
                        playMedia()
                    }, 2000);
                }
            }, 3000);

        }
    }

    var init = function () {
        let ul = document.querySelector(ulQueryStr)
        let liarray = ul.getElementsByTagName('li')
        for(var i = 0 ; i < liarray.length ; i++)
        {
            liarray[i].setAttribute('data-seq',i)
        }
        console.log(liarray)
    }

    var getCurrentActiveNode = function() {
        let result = 0
        let ul = document.querySelector(ulQueryStr)
        let liarray = ul.getElementsByTagName('li')
        for(var i = 0 ; i < liarray.length ; i++)
        {
            let className = liarray[i].getAttribute('class')
            if(undefined != className && null != className && className=='active')
            {
                result = liarray[i].getAttribute('data-seq')
            }
        }
        console.log('current active node:' + result)
        return result
    }

    var clickLiNode = function(index) {
        let ul = document.querySelector(ulQueryStr)
        let liarray = ul.getElementsByTagName('li')
        console.log('index:'+index +" li arrary length:"+ liarray.length)
        if(index >= liarray.length)
        {
            document.title = '【播放完成】》》》》》'
            return
        }
        liarray[index].click()
    }

    var playMedia = function() {
        console.log('play media')
        document.querySelector(mediaButtonStr).click()
    }

    var getMediaStatus = function() {

    }


})();